package com.coolpad.job.device.util.Function;

import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;

@Slf4j
public class FunctionUtils {


    public static <T,R> R retryIfException(T data, int time, Function<T,R> function) {

        int count = 0;
        while (count < time) {
            try {
                R res = function.apply(data);
                if(count != 0) {
                    log.info("retry {} succeed !", count);
                }
                return res;
            } catch (Exception e) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                log.error("process fail, retry {}",++count,e);
            }
        }
        return null;
    }

    public static void retryIfException(int time, Processor processor) {

        int count = 0;
        while (count < time) {
            try {
                processor.Process();
                if(count != 0) {
                    log.info("retry {} succeed !");
                }
                return;
            } catch (Exception e) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                log.error("process fail, retry {}",++count,e);
            }
        }
    }
}
